#include "pluginmanager.h"


PluginManager *PluginManager::m_instance = NULL;

/*!
    \fn PluginManager *PluginManager::instance()
    Get the unique plugin manager instance.
*/
PluginManager *PluginManager::instance()
{
    return m_instance;
}

/*!
    \fn PluginManager::PluginManager()
    Create a plugin manager. Should be done only once per application.
*/
PluginManager::PluginManager()
{
    m_instance = this;
}

/*!
    \fn PluginManager::~PluginManager()
    \internal
*/
PluginManager::~PluginManager()
{

}

void PluginManager::setPluginPath(const QString path)
{
    pluginPath = path;
    QDir dir(path);
    if(!dir.exists())
        return;
    QFileInfoList files = dir.entryInfoList(QStringList() << QString("*.dll"), QDir::Files | QDir::NoSymLinks);

    foreach (const QFileInfo &file, files){
        PluginSpec *spec = new PluginSpec;
        spec->ReadInfo(file);
        m_pluginSpecs.append(spec);
    }
}

QString PluginManager::getPluginPath(void)
{
    return pluginPath;
}

QList<PluginSpec *> PluginManager::getPluginsSpec()
{
    return m_pluginSpecs;
}

QList<IPluginFactory*> PluginManager::getFactoryList()
{
    return m_factories;
}

void PluginManager::addFactoryObject(IPluginFactory *obj)
{
    m_factories.append(obj);
}

void PluginManager::loadPlugins()
{
    foreach (PluginSpec *spec, m_pluginSpecs) {
        qDebug() << QString(QObject::tr("Loading %1 plugin")).arg(spec->name);
        spec->LoadLibrary();
    }

    foreach (PluginSpec *spec, m_pluginSpecs) {
        qDebug() << QString(QObject::tr("Initialize %1 plugin")).arg(spec->name);
        spec->InitializePlugin();
    }

    foreach (PluginSpec *spec, m_pluginSpecs) {
        qDebug() << QString(QObject::tr("Initialize %1 plugin extensions")).arg(spec->name);
        spec->InitializeExtensions();
    }

#if 0
    foreach (PluginSpec *spec, m_pluginSpecs) {
        //qDebug() << QString(QObject::tr("Loading %1 plugin")).arg(spec->name());
        loadPlugin(spec, PluginSpec::Initialized);
    }

    if (spec->hasError())
        return;
    if (destState == PluginSpec::Running) {
        spec->d->initializeExtensions();
        return;
    } else if (destState == PluginSpec::Deleted) {
        spec->d->kill();
        return;
    }
    foreach (PluginSpec *depSpec, spec->dependencySpecs()) {
        if (depSpec->state() != destState) {
            spec->d->hasError = true;
            spec->d->errorString =
                PluginManager::tr("Cannot load plugin because dependency failed to load: %1(%2)\nReason: %3")
                    .arg(depSpec->name()).arg(depSpec->version()).arg(depSpec->errorString());
            return;
        }
    }
    if (destState == PluginSpec::Loaded)
        spec->d->
    else if (destState == PluginSpec::Initialized)
        spec->d->initializePlugin();
    else if (destState == PluginSpec::Stopped)
        spec->d->stop();
#endif
}
